from playwright.sync_api import sync_playwright, Browser
from threading import Lock
import atexit


class BrowserManager:
    def __init__(self, headless=True, browser_type="chromium"):
        """
        初始化 Playwright 管理器
        :param headless: 是否启用无头模式
        :param browser_type: 浏览器类型 (chromium, firefox, webkit)
        """
        self.browser_type = browser_type
        self.headless = headless
        self.browser = None
        self.lock = Lock()
        self._initialize_browser()


    def _initialize_browser(self):
        """初始化浏览器实例（线程安全）"""
        with self.lock:
            if not self.browser or self.browser.is_connected():

                with sync_playwright() as p:
                    browser_class = getattr(p, self.browser_type)
                    self.browser = self.__create_undisplay_browser(browser_class) if self.headless else self.__create_display_browser(browser_class)

    def get_browser(self):
        if self.browser is None or self.browser.is_connected():
            self._initialize_browser()
        return self.browser

    def shutdown(self):
        """关闭浏览器并释放资源"""
        with self.lock:
            if self.browser and not self.browser.is_connected():
                self.browser.close()

    # 有头模式
    def __create_display_browser(self,browser_class):

        return browser_class.launch(headless=False)

    # 无头模式

    def __create_undisplay_browser(self,browser_class):
        # 移除user_agent，仅保留launch支持的参数
        launch_options = {
            "headless": True,
            "args": [
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
                "--start-maximized"
            ]
        }

        return browser_class.launch(**launch_options)
